package fr.mywiki.business.xml;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import fr.mywiki.business.log.LogManager;

public class AJAXManager {

	public static final String TEXT_CONTENT_TYPE = "text";
	public static final String JSON_CONTENT_TYPE = "json";
	public static final String XML_CONTENT_TYPE = "xml";
	
	public static final boolean verbose = LogManager.DISPLAY_IN_LOG;

	public static void sendResponse(String contentType, String returnText,
			HttpServletResponse response) throws IOException {
		if(verbose)
			LogManager.println("Sent to client : " + returnText);
		if (TEXT_CONTENT_TYPE.equals(contentType)) {
			response.setContentType("text/plain; charset=ISO-8859-1");
		} else if (JSON_CONTENT_TYPE.equals(contentType)) {
			response.setContentType("application/javascript");
		} else if (XML_CONTENT_TYPE.equals(contentType)) {
			response.setContentType("text/xml; charset=ISO-8859-1");
		}
		PrintWriter print = new PrintWriter(response.getOutputStream());
		print.write(returnText);
		print.flush();
		response.flushBuffer();
	}
	
	public static void sendResponse(String contentType, Map elements, Map objects,
			HttpServletResponse response) throws IOException {
		sendResponse(contentType, buildResponse(elements,objects),response);
	}
	
	public static String buildResponse(Map elements, Map objects) {
		StringBuffer strXML = new StringBuffer();
		strXML.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
		strXML.append("<ajax-response>");
		Iterator itElements = elements.keySet().iterator();
		while (itElements.hasNext()) {
			String key = (String) itElements.next();
			String value = (String) elements.get(key);
			strXML.append("<response type=\"element\" id=\"" + key + "\">");
			strXML.append(value);
			strXML.append("</response>");
		}
		Iterator itObjects = objects.keySet().iterator();
		while (itObjects.hasNext()) {
			String key = (String) itObjects.next();
			String value = (String) objects.get(key);
			strXML.append("<response type=\"object\" id=\"" + key + "\">");
			strXML.append(value);
			strXML.append("</response>");
		}
		strXML.append("</ajax-response>");
		return strXML.toString();
	}
	
	public static String getStringDecoded(String l_string) throws Exception {
		return new String(l_string.getBytes(), "UTF-8");
	}
}
